/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.application.configuration;

import com.jb.framework.pm.XMLPersistentManager;
import com.jb.web.context.WebContext;
import com.jb.framework.ModelBean;

import java.io.File;
import java.io.Serializable;

/**
 * ConfigBean is a container holds configuration information for
 * the system. It is persisted with a XMLPersistentManager.
 **/
public class ConfigBean extends ModelBean implements Serializable{
    private static final String JAVABASE = "jb";
    public static final String CONFIG = "config";
    public static final String WEB_INF = "WEB-INF";
    private String applTop;
    private String userTop;

    public void setUserTop(String userTop) {
        this.userTop = userTop;
    }

    public String getUserTop() {
        return (userTop == null) ? applTop : userTop;
    }

    public void createDefault(WebContext pCtx) {
        //
    }

    /**
     * loads configuration. This should be called only once when applicaiton
     * is loaded. It loads configuration and try to initialized the application.
     * */
    public boolean load(String path) {
        StringBuffer loc = new StringBuffer(path).append(WEB_INF).append(File.separator).append(JAVABASE);
        XMLPersistentManager pm = new XMLPersistentManager(loc.toString() + File.separator + CONFIG);
        this.applTop = loc.toString();
        return pm.load(this);
    }

    /**
     * saves configuration
     */
    public void update() {
        XMLPersistentManager pm = new XMLPersistentManager(applTop + File.separator + CONFIG);
        pm.save(this, true);
    }

    String getApplTop() {
        return applTop;
    }
}
